const _ = require('lodash');


const prefix = '/api/proposal';
module.exports = app => {
    const {router, middleware} = app;

    router.get(prefix + '/projects', middleware.api(), async ctx => {
        if (ctx.user.level.id <= 2) {
            ctx.body = await app.model.Project.findAll({where: {end_at: {[app.Sequelize.Op.gt]: new Date()}}});
        } else {
            const user = ctx.app.model.User.build({id: ctx.user.id}, {isNewRecord: false});
            ctx.body = await user.getProjectClient({
                attributes: ['id', 'name'],
                where: {end_at: {[app.Sequelize.Op.gt]: new Date()}}
            });
        }
    });

    //
    router.get(prefix + '/project/:project_id', middleware.api(), async ctx => {
        const user = ctx.app.model.User.build({id: ctx.user.id}, {isNewRecord: false});
        let project;

        if (ctx.user.level.id <= 2)
            project = await app.model.Project.findByPk(ctx.params.project_id);
        else
            [project] = await user.getProjectClient({where: {id: ctx.params.project_id}});

        if (!project)
            return ctx.helper.error('不存在的项目');

        let anchors = await project.getAnchor({
            include: [
                {model: app.model.Platform},
                {model: app.model.DetailAnchorOption, as: 'option'},
                {model: app.model.DetailAnchorData, as: 'data', limit: 1, order: [['fans', 'desc']]},
            ]
        });

        let platforms = _.map(anchors, 'platform.name');
        let categories = [];
        anchors.forEach((a, i) => {
            anchors[i] = a = a.toJSON();
            if (a.option && _.isArray(a.option.categories))
                categories.push(...a.option.categories);
            if (a.data[0])
                a.fans = a.data[0].fans;
            else
                a.fans = 0;
            delete a.data;
        });
        anchors = _.orderBy(anchors, 'fans', 'desc');
        categories = _.compact(_.uniq(categories));
        ctx.body = {project, platforms, categories, anchors};
    });

    router.get(prefix + '/categories', middleware.api(), async ctx => {
        const where = {};
        const search = ctx.query.search;
        if (!_.isEmpty(search))
            where.name = {[app.Sequelize.Op.like]: '%' + search + '%'};
        ctx.body = _.map(await app.model.DailyCategory.findAll({where}), 'name');
    });
};